package com.example.idlefish.MyAccount.activity


import android.annotation.*
import android.os.*
import android.os.Message
import android.util.Log
import android.view.*
import android.widget.*
import androidx.appcompat.app.*
import androidx.recyclerview.widget.*
import com.example.idlefish.*
import com.example.idlefish.MyAccount.contract.HomepageContract
import com.example.idlefish.MyAccount.pojo.*
import com.example.idlefish.PublicModule.ApplicationConst
import com.example.idlefish.PublicModule.NetworkSettings
import com.example.idlefish.databinding.*
import com.fasterxml.jackson.databind.ObjectMapper
import com.google.gson.*
import okhttp3.*
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody.Companion.toRequestBody
import java.io.*

class ChatActivity  : AppCompatActivity()  {
    private lateinit var binding: MyaccountChatgptBinding
    private var index = -1
    private var position = -1
    private val client = OkHttpClient()
    private val handler = Handler(Looper.getMainLooper())
    private val mediaType = "application/json;charset=utf-8".toMediaTypeOrNull()
    private val message = Message()
    private val mapper = ObjectMapper()


    override fun onCreate(savedInstanceState: Bundle?) {

        super.onCreate(savedInstanceState)
        binding = MyaccountChatgptBinding.inflate(layoutInflater)
        setContentView(binding.root)


        // val id = CommonUtil.getSerializable(intent, "id", Long::class.java)
        val id = intent.getLongExtra("id", -1)
        Log.i("日志ChatActivity接受信息", "id: $id")
        
        setSupportActionBar(binding.toolbar)
        supportActionBar?.setDisplayHomeAsUpEnabled(true);// 添加默认的返回图标
        supportActionBar?.setHomeButtonEnabled(true); // 设置返回键可用

        binding.loading.hide()
        binding.userInput.visibility = View.GONE
        binding.aiOutput.visibility = View.GONE

        binding.sendGPTButton.setOnClickListener {
            val message = binding.inputText.text.toString()
            if (message.isEmpty()) {
                Toast.makeText(applicationContext, "消息不能为空", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            binding.loading.show()
            binding.userInput.visibility = View.VISIBLE
            binding.userInput.text = message
            binding.inputText.text.clear()
            sendPost(message)
        }
    }

    private fun sendPost(chatMessage: String) {
        try {
            val request = Request.Builder().url(NetworkSettings.HTTP + "chat")
                .post(mapper.writeValueAsString(chatMessage).toRequestBody(mediaType)
                ).build()

            client.newCall(request).enqueue(object : Callback {
                override fun onFailure(call: Call, e: IOException) {
                    message.what = ResponseCode.REQUEST_FAILED
                    handler.post {
                        Utils.showMessage(applicationContext, message)
                    }
                    e.printStackTrace()
                }

                override fun onResponse(call: Call, response: Response) {
                    val gson = Gson()
                    val responseData = response.body?.string()
                    val data = gson.fromJson(responseData, GPTResult::class.java)
                    val info = data.data[0].message.content
                    Log.i("日志  ai返回数据", info)


                     handler.post {
                         binding.loading.hide()
                         binding.aiOutput.visibility = View.VISIBLE
                         binding.aiOutput.text = info

                    }
                }
            })
        } catch (e: Exception) {
            message.what = ResponseCode.JSON_SERIALIZATION
            Log.i("捕获异常", message.toString())
            e.printStackTrace()
        }

    }



}